/*
 * @Author: jasper
 * @Date: 2022-03-04 16:25:24
 * @LastEditors: baron
 * @LastEditTime: 2024-11-28 14:21:11
 * @Description: 埋点封装
 */
import { setBuriedPoint } from '@/apis/common';
import { getOpenUnionId } from '@/utils/getOpenUnionId';
const utils = require('./util');

let union_id = null,
    open_id = null,
    startTime = null;

export const buriedPoint = async (params = {}) => {
    try {
        const pages = getCurrentPages();
        params.showLoading = false;
        if (!union_id || !open_id) {
            const { unionId, openId, sessionKey } = await getOpenUnionId();  
            union_id = unionId;
            open_id = openId;
            params.unionId = unionId;
            params.openId = openId;    
        } else {
            params.unionId = union_id || JSON.parse(uni.getStorageSync('userInfo') || '{}').unionId;
            params.openId = open_id || JSON.parse(uni.getStorageSync('userInfo') || '{}').openId;
        }
        if (params.code === 1) {
            startTime = Date.parse(new Date());
        }
        if (params.code === 5) {
            params.duration = (Date.parse(new Date()) - startTime) / 1000;
        }
        params.pageUrl = utils.createUrlByObj(pages[pages.length - 1].route, pages[pages.length - 1].options);
        if (pages.length > 1) {
            params.refererUrl = pages[pages.length - 2]
                ? utils.createUrlByObj(pages[pages.length - 2].route, pages[pages.length - 2].options)
                : undefined;
            params.refererName = pages[pages.length - 2] ? getPageName(2)?.name : undefined;
            params.refererCode = pages[pages.length - 2] ? getPageName(2)?.code : undefined;
        }
        params.pageName = params.pageName || getPageName().name;
        params.pageCode = getPageName().code;
        const res = await setBuriedPoint(params);
        return res;
    } catch (error) {
        console.log(error, '埋点失败');
    }
};

function getPageName(num = 1) {
    const pages = getCurrentPages();
    const routerList = [
        {
            name: '素材或知识库详情页',
            page: '/material/materialDetail',
            code: 800001
        },
        {
            name: '知识库-PDF打开中间页',
            page: '/training/knowledge/openPDF',
            code: 800002
        },
        {
            name: '知识库-打开PDF',
            page: '/training/knowledge/index',
            code: 800003
        },
    ];
    const arr = routerList.filter(item => {
        return pages[pages.length - num]?.$page?.fullPath?.includes(item.page);
    });    
    let name = arr[0]?.name || '君选优导';
    let code = arr[0]?.code;
    return {
        name,
        code
    };
}
